<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        table {
            width: 739px;
            height: 222px;
            border-collapse: collapse;
            margin: 100px auto;
        }

        th {
            background-color: #3999cc;
        }

        table,
        tr,
        td {
            border: 1px solid #d3d3d3;
            color: #3a3946;
            font-size: 26px;
            text-align: center;
        }
    </style>
</head>

<body>
    <table>
        <tr>
            <th>
                <input type="checkbox" class="all">全选
            </th>
            <th>商品</th>
            <th>商家</th>
            <th>价格</th>
        </tr>
        <tr>
            <td> <input type="checkbox" class="ck"> </td>
            <td>小米手机</td>
            <td>小米</td>
            <td>￥1999</td>
        </tr>
        <tr>
            <td> <input type="checkbox" class="ck"> </td>
            <td>小米手机</td>
            <td>小米</td>
            <td>￥1999</td>
        </tr>
        <tr>
            <td> <input type="checkbox" class="ck"> </td>
            <td>小米手机</td>
            <td>小米</td>
            <td>￥1999</td>
        </tr>
    </table>

    <script>
        const all = document.querySelector('.all')
        const ck = document.querySelectorAll('.ck')
        const l = document.querySelectorAll('.ck:checked').length
        all.addEventListener('click', function () {
            // 简单写法
            for (let i = 0; i < ck.length; i++) {
                ck[i].checked = all.checked
            }

            // if (all.checked === false) {
            //     for (let i = 0; i < ck.length; i++) {
            //         ck[i].checked = false
            //     }
            // }
            // else {
            //     for (let i = 0; i < ck.length; i++) {
            //         ck[i].checked = true
            //     }
            // }
        })
        let num = 0
        for (let i = 0; i < ck.length; i++) {
            ck[i].addEventListener('click', function () {
                all.checked = document.querySelectorAll('.ck:checked').length === ck.length
            })
        }
    </script>
</body>

</html>